package pais.db;

import java.io.IOException;

import papos.rowset.DuplicatedKeyValueException;
import papos.rowset.StorageSystem;
import pasys.error.PaposException;


public class KeywordTable implements TableInterface {
  private static KeywordTable INST_ = null;

  public static KeywordTable createInstance( String path ) {
    assert( INST_ == null );
    INST_ = new KeywordTable(path);
    return INST_;
  }
  public static KeywordTable getInstance() {
    return INST_;
  }


  private String path_;
  private StorageSystem storage_;
  public KeywordTable(String path) {
    path_ = path;
  }

  public void open(boolean writable) throws IOException {
    Keyword sampleInstance = new Keyword();

    try {
      storage_ = StorageSystem.open(	
          path_, 
          "keyword-table", 
          sampleInstance, 
          sampleInstance.getKeyDesc(),
          writable);
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      e.printStackTrace();
      PAISDB.exit("While Opening the keyword-table : "+e.toString());
    }
  }
  public void sync() throws IOException, PaposException {
    storage_.sync();
  }

  public void close() throws IOException, PaposException {
    StorageSystem.close(storage_);
    storage_ = null;
  }

  public StorageSystem getStorage() {
    return storage_;
  }

  public void insert(String keyword, long UID, int offset) throws PaposException {
    long KID = PAISSystemTable.getNextKID();
    Keyword kw = new Keyword(KID, keyword, UID, offset);
    try {
      if ( ! storage_.insert(kw) ) {
        PAISDB.exitPrintingStack("Failed to insert "+kw.toString());
      }
    } catch (DuplicatedKeyValueException e) {
      e.printStackTrace();
      PAISDB.exit("Duplicated key error wile inserting "+kw.toString()+"\n Error:"+e.toString());
    }
  }
  /* Delete all keywords with UID */
  public void deleteAll(long UID) {
    Keyword kw = new Keyword();
    kw.setUID(UID);
    try {
      if ( storage_.find("UID_", kw) ) {
        do {
          if ( ! storage_.delete(kw) ) {
            PAISDB.exitPrintingStack("Failed to delete "+kw.toString());
          }
          kw.setUID(UID);
        } while ( storage_.find("UID_", kw) );
      }
    } catch (Exception e) {
      e.printStackTrace();
      PAISDB.exit("Exception while deleting all keywords.\n Current Key="+kw.toString()+"\nError:"+e.toString());
    }
  }
}
